package com.crm.business.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.business.admin.mapper.AdminUserMapper;
import com.crm.business.crm.mapper.BillCrmTrainingMapper;
import com.crm.business.crm.service.*;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import com.crm.common.admin.entity.PO.AdminUser;
import com.crm.common.constant.Constants;
import com.crm.common.crm.entity.BO.BillCrmTrainingBO;
import com.crm.common.crm.entity.PO.*;
import com.crm.common.ka.core.common.Result;
import com.crm.common.ka.core.redis.Redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class BillCrmTrainingServiceImpl extends BaseServiceImpl<BillCrmTrainingMapper, BillCrmTraining> implements IBillCrmTrainingService {
    @Autowired
    private BillCrmTrainingMapper crmTrainingMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private Redis redis;
    @Autowired
    private ICrmFieldSortService crmFieldSortService;
    @Autowired
    private ICrmFieldService crmFieldService;
    @Autowired
    private ICrmRoleFieldService crmRoleFieldService;
    @Autowired
    private ICrmDeptFieldService crmDeptFieldService;


    @Override
    public IPage<BillCrmTraining> queryPageList(BillCrmTrainingBO billOrderPoolBO) {
        IPage<BillCrmTraining> page = new Page<>(billOrderPoolBO.getPage(), billOrderPoolBO.getLimit());
        QueryWrapper<BillCrmTraining> queryWrapper = new QueryWrapper<>();
        IPage<BillCrmTraining> trainingPage = crmTrainingMapper.selectPage(page, queryWrapper);
        List<BillCrmTraining> pageRecords = page.getRecords();
        List<BillCrmTraining> newPageRecords =new ArrayList<>();
        for (BillCrmTraining crmTraining : pageRecords) {
            if (crmTraining.getCreateUserId() != null) {
                QueryWrapper<AdminUser> adminUserQueryWrapper = new QueryWrapper<>();
                adminUserQueryWrapper.select("realname").eq("user_id", crmTraining.getCreateUserId());
                AdminUser adminUser = adminUserMapper.selectOne(adminUserQueryWrapper);
                crmTraining.setCreateUserName(adminUser.getRealname());
            }
            if (crmTraining.getUpdateUserId() != null) {
                QueryWrapper<AdminUser> adminUserQueryWrapper = new QueryWrapper<>();
                adminUserQueryWrapper.select("realname").eq("user_id", crmTraining.getUpdateUserId());
                AdminUser adminUser = adminUserMapper.selectOne(adminUserQueryWrapper);
                crmTraining.setUpdateUserName(adminUser.getRealname());
            }
            newPageRecords.add(crmTraining);

        }
        return trainingPage.setRecords(newPageRecords);
    }

    @Override
    public Result<BillCrmTraining> queryById(Integer id) {
        BillCrmTraining crmOrderPool = crmTrainingMapper.selectById(id);
        return Result.ok(crmOrderPool);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> update(BillCrmTraining crmTraining) {
        BillCrmTraining oldTraining = crmTrainingMapper.selectById(crmTraining.getId());;
        crmTraining.setUpdateUserId(UserUtil.getUserId());
        crmTraining.setUpdateTime(new Date());
        int i = crmTrainingMapper.updateById(crmTraining);
        if(i > 0){
            BillCrmTraining billCrmTraining = crmTrainingMapper.selectById(crmTraining.getId());
            redis.set(Constants.ORG_TRAINING,billCrmTraining);
        }

        // 变更字段
        if(!ObjectUtil.equal(oldTraining.getStatus(), crmTraining.getStatus())){
            changeField(crmTraining.getStatus());
        }

        return Result.ok();
    }

    /**
     * 查询机构训练营模式开启状态
     * @return
     */
    @Override
    public Result queryTrainingStatus(){
        BillCrmTraining crmTraining = redis.get(Constants.ORG_TRAINING);
        if(crmTraining != null){
            return Result.ok(crmTraining.getStatus());
        }

        BillCrmTraining by = query().one();
        if(by == null){
            return Result.error("训练营模式不存在");
        }
        redis.set(Constants.ORG_TRAINING,by);
        return Result.ok(by.getStatus());
    }


    @Transactional(rollbackFor = Exception.class)
    public void changeField(Integer status){
        LambdaQueryWrapper<CrmFieldSort> wrapper = new LambdaQueryWrapper<>();
        crmFieldSortService.getBaseMapper().delete(wrapper);

        if(status == 0){
            LambdaUpdateWrapper<CrmField> fieldWrapper = new LambdaUpdateWrapper<>();
            fieldWrapper.set(CrmField::getIsHidden, 1);
            fieldWrapper.set(CrmField::getIsShowFrom, 0);
            fieldWrapper.in(CrmField::getFieldName, "training_periods","teacher_id");
            crmFieldService.update(fieldWrapper);

            LambdaQueryWrapper<CrmRoleField> roleFieldWrapper = new LambdaQueryWrapper<>();
            roleFieldWrapper.in(CrmRoleField::getFieldName, "training_periods","teacher_id");
            crmRoleFieldService.getBaseMapper().delete(roleFieldWrapper);

            LambdaQueryWrapper<CrmDeptField> deptFieldWrapper = new LambdaQueryWrapper<>();
            deptFieldWrapper.in(CrmDeptField::getFieldName, "training_periods","teacher_id");
            crmDeptFieldService.getBaseMapper().delete(deptFieldWrapper);
        }else{
            QueryWrapper<CrmField> fieldQueryWrapper = new QueryWrapper<>();
            fieldQueryWrapper.in("field_name", "training_periods","teacher_id");
            List<CrmField> fieldList = crmFieldService.query().getBaseMapper().selectList(fieldQueryWrapper);

            LambdaUpdateWrapper<CrmField> fieldWrapper = new LambdaUpdateWrapper<>();
            fieldWrapper.set(CrmField::getIsHidden, 0);
            fieldWrapper.set(CrmField::getIsShowFrom, 1);
            fieldWrapper.in(CrmField::getFieldName, "training_periods","teacher_id");
            crmFieldService.update(fieldWrapper);

            List<Map<Integer, Integer>> roleFields = crmRoleFieldService.queryRoleFieldForGroup();
            for(Map<Integer, Integer> map : roleFields){
                for (CrmField crmField : fieldList){
                    if(crmField.getLabel().equals(map.get("label"))){
                        CrmRoleField roleField = new CrmRoleField();
                        roleField.setRoleId(map.get("roleId"));
                        roleField.setLabel(crmField.getLabel());
                        roleField.setFieldId(crmField.getFieldId());
                        roleField.setFieldName(crmField.getFieldName());
                        roleField.setName(crmField.getName());
                        roleField.setAuthLevel(3);
                        roleField.setOperateType(1);
                        roleField.setFieldType(crmField.getFieldType());
                        crmRoleFieldService.save(roleField);
                    }
                }
            }

            QueryWrapper<CrmDeptField> deptFieldWrapper = new QueryWrapper<>();
            deptFieldWrapper.select("dept_id");
            List<Map<Integer, Integer>> deptFields = crmDeptFieldService.queryDeptFieldForGroup();

            for(Map<Integer, Integer> map : deptFields){
                for (CrmField crmField : fieldList){
                    if(crmField.getLabel().equals(map.get("label"))){
                        CrmDeptField deptField = new CrmDeptField();
                        deptField.setDeptId(map.get("deptId"));
                        deptField.setLabel(crmField.getLabel());
                        deptField.setFieldId(crmField.getFieldId());
                        deptField.setFieldName(crmField.getFieldName());
                        deptField.setName(crmField.getName());
                        deptField.setAuthLevel(3);
                        deptField.setOperateType(1);
                        deptField.setFieldType(crmField.getFieldType());
                        crmDeptFieldService.save(deptField);
                    }
                }
            }
        }
    }


}
